const initUserMedia = (errorFunc, successFunc) => {
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }

    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = (constraints) => {
            var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
            if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
            }
            return new Promise((resolve, reject) => {
            getUserMedia.call(navigator, constraints, resolve, reject);
            });
        }
    }

    var mediaOpts = {
        // audio: audioVideoDevices.audioinput || audioVideoDevices.audiooutput,
        audio: true,
        //判断如果是视频通话就调用前置摄像头，facingMode: "user"调用前置摄像头，如果不是视屏通话就不使用摄像头
        video: {
          facingMode: "user",
        }
      }

      navigator.mediaDevices.getUserMedia(mediaOpts).then(stream => {
        // 成功获取媒体流后调用成功回调函数
        successFunc(stream);
      }).catch(error => {
        
        // 获取媒体流失败时调用失败回调函数
        errorFunc(error);
      });
};

const initPeerConnection = (PeerConnection, remoteVideo) => {
    // if (PeerConnection !== null && PeerConnection !== undefined) {
    //     return null;
    //   }
      PeerConnection = (window.webkitRTCPeerConnection 
        || window.mozRTCPeerConnection 
        || window.RTCPeerConnection || undefined);

        //using Google public stun server,turn中继服务器需要自己搭建，可参考网上coturn搭建教程
        //此处指定了服务器，是 Google 的 STUN 服务器，
        var configuration = {
            "iceServers": [{
                'urls': 'stun:stun.l.google.com:19302'
            }]
        };
       
        let yourConn = new PeerConnection(configuration);


        yourConn.ontrack = (event) => {
          
          // 获取远端流
          const stream = event.streams[0];
          // 获取远端track
          const track = event.track;
          console.log("被叫用户向对等连接添加流-- track->", track);
          console.log("被叫用户向对等连接添加流--->", stream);
            //将远程流显示到页面
            // 将远端流添加到video或audio元素中
          if (track.kind === 'video') {
            remoteVideo.srcObject = stream
          }
            
        };

        return yourConn;

        
}
const webrtcUtils = {
    initUserMedia,
    initPeerConnection
  }
  export default webrtcUtils